package cn.tedu.charging.order.config;

import cn.tedu.charging.order.dao.repository.OrderRepository;
import cn.tedu.charging.order.feign.CostClient;
import cn.tedu.charging.order.feign.UserClient;
import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContext;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;

/**
 * mqtt 客户端配置
 */
@Configuration
public class MqttConfig {

    /**
     * 用户名
     */
    private String username = "admin";

    /**
     * 密码
     */
    private String password = "public";

    /**
     * 地址 连接的默认端口号 1883
     */
    private String host = "tcp://localhost:1883";

    /**
     * 客户端id
     */
    private String clientId = "order_service_client";

    private MqttClient mqttClient;

    //todo:如果不写dao层分开业务代码,会发生mqttConfig和orderServiceImpl的耦合
/*    @Resource
    //@Lazy
    //todo:解决循环依赖的方法可以有添加@Lazy注解解决
    //private OrderService orderService;
    private OrderRepository orderRepository;

    @Resource
    private CostClient costClient;

    @Resource
    private UserClient userClient;*/

    @Resource
    private MqttContext mqttContext;

    //todo:2024-06-27 创建mqtt客户端
    @Bean
    public MqttClient mqttClient() throws MqttException {
        //通过链接地址和客户端id进行连接
        //客户端id的目的是告诉我们的服务器,谁在链接它
        mqttClient = new MqttClient(host,clientId);

        //连接相关的配置
        MqttConnectOptions connOpts = new MqttConnectOptions();

        //用户名
        connOpts.setUserName(username);

        //密码
        connOpts.setPassword(password.toCharArray());

        //自动重连
        connOpts.setAutomaticReconnect(true);
        //版本号设置
        connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

        //清理会话session
        connOpts.setCleanSession(true);

        //创建mqtt消费者
        MqttConsumer mqttConsumer = new MqttConsumer(mqttClient,mqttContext);

        //设置消费者
        mqttClient.setCallback(mqttConsumer);

        //基于上面配置号的连接相关的配置,进行连接
        mqttClient.connect(connOpts);

        System.out.println(mqttClient);
        return mqttClient;
    }
}
